package com.xian.im.modules.command.group.handler;

import com.xian.im.common.constant.CommandCodeConstant;
import com.xian.im.common.constant.CommandConstant;
import com.xian.im.common.exception.BusinessException;
import com.xian.im.common.model.dto.GroupDto;
import com.xian.im.common.model.session.SessionUser;
import com.xian.im.common.proto.MsgRequest;
import com.xian.im.common.proto.MsgResponse;
import com.xian.im.common.utils.bussiness.XimResponseUtil;
import com.xian.im.common.utils.sys.SpringContextHolder;
import com.xian.im.modules.avchat.manager.ImGroupManager;
import com.xian.im.modules.command.group.AbsGroupCommand;

/**
 * @program: xian-im-server
 * @description: 退出群组 群员操作基于内存操作
 * @author: liru.xian
 * @create: 2021-01-28 22:35
 **/
public class GroupQuit extends AbsGroupCommand {

    @Override
    public void handler(MsgRequest request, String ctx, GroupDto groupEntity) {
        if (userChannelClient().hasGroup(request.getGroupUniqueId(), ctx)) {
            String groupUniqueId = request.getGroupUniqueId();
            groupChannelClient().quit(ctx,groupUniqueId);
            SessionUser session = userChannelClient().session(ctx);
            MsgResponse success = XimResponseUtil.buildSuccess(session);
            success.setGroupUniqueId(groupEntity.getGroupUniqueId());
            success.setBody(success.getUser().getNickname() + "退出了房间");
            success.setCmd(CommandConstant.SYSTEM_CMD);
            //发送消息
            groupChannelClient().pushGroupSystemMessage(groupUniqueId,success);
        } else {
            throw new BusinessException("请先加入群组，操作失败");
        }
    }

    /**
     * 群组code
     *
     * @return
     */
    @Override
    public String cmdCode() {
        return CommandCodeConstant.GROUP_QUIT;
    }

    private static ImGroupManager  groupManager(){
        return SpringContextHolder.getBean(ImGroupManager.class);
    }
}
